using System.Collections.Generic;
using Photon;
using UnityEngine;

public class CarFunction : Photon.MonoBehaviour
{
	private ItemFunctions s_ItemFunctions;

	public int m_maxPlayersInCar;

	public bool m_PlayerInCar;

	public List<string> playerInCar;

	public bool m_ObjectIsKinematic;

	private GameObject playerOwner;

	[HideInInspector]
	public RCC_CarControllerV3 s_CarController;

	private Rigidbody m_Rigidibody;

	public GameObject allSources;

	private void Awake()
	{
		s_ItemFunctions = GetComponent<ItemFunctions>();
		for (int i = 0; i < m_maxPlayersInCar; i++)
		{
			playerInCar.Add(string.Empty);
		}
		s_CarController = GetComponent<RCC_CarControllerV3>();
		m_Rigidibody = GetComponent<Rigidbody>();
	}

	private void Start()
	{
	}

	private void Update()
	{
		if (!SavesAllFunctions.Local && !base.photonView.isMine && m_Rigidibody != null)
		{
			m_Rigidibody.isKinematic = true;
		}
	}

	public void OnPhotonSerializeView(PhotonStream stream, PhotonMessageInfo info)
	{
		if (stream.isWriting)
		{
			stream.SendNext(m_PlayerInCar);
			for (int i = 0; i < playerInCar.Count; i++)
			{
				stream.SendNext(playerInCar[i]);
			}
			return;
		}
		m_PlayerInCar = (bool)stream.ReceiveNext();
		for (int j = 0; j < playerInCar.Count; j++)
		{
			playerInCar[j] = (string)stream.ReceiveNext();
		}
		if (m_PlayerInCar)
		{
			m_Rigidibody.isKinematic = true;
		}
	}

	public void SitDownOrQuitInCar(bool active, bool driver)
	{
		Debug.Log("my " + active + " DRiver " + driver);
		if (driver)
		{
			s_CarController.enabled = active;
		}
		m_PlayerInCar = active;
		if (s_CarController.AllAudioSources != null)
		{
			allSources = s_CarController.AllAudioSources;
		}
	}

	public void SitDownCar(string playerName)
	{
		if (playerInCar.Contains(playerName))
		{
			return;
		}
		for (int i = 0; i < m_maxPlayersInCar; i++)
		{
			if (playerInCar[i] == string.Empty)
			{
				playerInCar[i] = playerName;
				break;
			}
		}
	}

	public void ExitCar(string playerName)
	{
		if (playerInCar.Contains(playerName))
		{
			for (int i = 0; i < m_maxPlayersInCar; i++)
			{
				if (playerInCar[i] == playerName)
				{
					playerInCar[i] = string.Empty;
					break;
				}
			}
		}
		SortPlayer();
		OwnerShip(CarDriver());
	}

	public void SortPlayer()
	{
		string empty = string.Empty;
		for (int i = 0; i < playerInCar.Count; i++)
		{
			for (int j = 0; j < playerInCar.Count - 1; j++)
			{
				if (playerInCar[j] == string.Empty)
				{
					empty = playerInCar[j + 1];
					playerInCar[j + 1] = playerInCar[j];
					playerInCar[j] = empty;
				}
			}
		}
	}

	public void OwnerShip(bool active)
	{
		if (active)
		{
			base.photonView.RequestOwnership();
		}
	}

	public bool CarDriver()
	{
		if (playerInCar.Count > 0 && playerInCar[0] == PhotonNetwork.playerName)
		{
			return true;
		}
		return false;
	}
}
